package high;

import com.fasterxml.jackson.databind.node.NullNode;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/*class pencils implements Runnable {             //不加锁，返回617，铅笔库存并没有清空，发生了线程安全问题
    public static int num=1000;
    @Override
    public void run() {
        num--;
    }
}*/

/*class pencils implements Runnable {             //使用atomicInteger原子类保证了线程安全问题
    public static AtomicInteger num=new AtomicInteger(1000);
    @Override
    public void run() {
        num.decrementAndGet();
    }
}*/

/*class pencils implements Runnable {         //使用synchronize锁保证了线程安全问题
    public static int num=1000;
    public static final Object lock=new Object();
    @Override
    public void run() {
        synchronized (lock) {
            num--;
        }
    }
}*/

class pencils implements Runnable{
    public static int num=1000;
    private static ReentrantLock lock=new ReentrantLock();
    @Override
    public void run() {
        lock.lock();
        num--;
        lock.unlock();
    }
}
/**
 * @author 47868
 */
public class Synchronized {
    public static void main(String[] args) throws InterruptedException {
        pencils pen = new pencils();
        ExecutorService exec = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 1000; i++) {
            exec.execute(pen);
        }
        TimeUnit.SECONDS.sleep(2);
        System.out.println(pencils.num);
        exec.shutdown();
    }
}
